package com.marvin.springBoot.service;

import com.marvin.springBoot.persistence.DemoUserEntity;
import com.marvin.springBoot.persistence.DemoUserType;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;

/**
 * @author marvin.ma
 * @create 2017-09-30 15:04
 * @desc ${DESCRIPTION}
 **/
@Service
public class DemoUserSpecifications {
    public Specification<DemoUserEntity> lastNameIsLike(String searchTerm) {

        Specification<DemoUserEntity> spec = new Specification<DemoUserEntity>() {
            public Predicate toPredicate(Root<DemoUserEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                Predicate p1 = cb.like(root.get("name").as(String.class), "%"+ "刘明" +"%");
                Predicate p2 = cb.equal(root.get("id").as(Long.class), 115);
                Predicate p3 = cb.gt(root.get("age").as(Integer.class), 28);
                SetJoin<DemoUserEntity, DemoUserType> depJoin = root.join(root.getModel().getSet("userType",DemoUserType.class) , JoinType.LEFT);

                Predicate p4 = cb.equal(depJoin.get("typeId").as(Long.class), 1001);
                //把Predicate应用到CriteriaQuery去,因为还可以给CriteriaQuery添加其他的功能，比如排序、分组啥 的
                query.where(cb.and(cb.and(p3,cb.or(p1,p2)),p4));
                //添加分组的功能
                query.orderBy(cb.desc(root.get("id").as(Long.class)));
                return query.getRestriction();
            }
        };
        return spec;
        //return new Specification<DemoUserEntity>() {
        //    @Override
        //    public Predicate toPredicate(Root<DemoUserEntity> userRoot, CriteriaQuery<?> query, CriteriaBuilder cb) {
        //        String likePattern = getLikePattern(searchTerm);
        //        return cb.like(cb.lower(userRoot.<String>get(DemoUser_.name)), likePattern);
        //    }
        //
        //    private String getLikePattern(final String searchTerm) {
        //        StringBuilder pattern = new StringBuilder();
        //        pattern.append(searchTerm.toLowerCase());
        //        pattern.append("%");
        //        return pattern.toString();
        //    }
        //};
    }
}
